import 'package:badges/badges.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:intl/intl.dart';
import 'package:sample2/components/alert_helper.dart';
import 'package:sample2/components/notification/user_info.dart';
import 'package:sample2/helper/app_helper.dart';
import 'package:sample2/pages/home/product/home_content1.dart';
import 'package:sample2/pages/home/home_content2.dart' deferred as home_content2;
import 'package:sample2/pages/home/home_content3.dart' deferred as home_content3;
import 'package:sample2/pages/home/home_content_last.dart' deferred as home_content_last;
import 'package:sample2/pages/login/login_page.dart' deferred as login_page;
import 'package:sample2/pages/my_side_menu.dart';
import 'package:sample2/utils/networking.dart';

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return const HomePageNormalPage();
  }

    @override
  void dispose() {
    //release resource here
    super.dispose();
  }

}

class HomePageNormalPage extends StatefulWidget {
  const HomePageNormalPage({super.key});
  @override
  State<StatefulWidget> createState() {
    return HomePageNormalPageState();
  }
}

class HomePageNormalPageState extends State with TickerProviderStateMixin {
  String bl = "";
  int _currentIndex = 0;
  late TabController _tabController;
  final tabs = [
    "GridView",
    "Wrap",
    "Flow",
    // "Tab 4",
    // "Tab 5",
    "Tab Last",
  ];
  int? logoutlistener;

  @override
  void initState() {
    _tabController = TabController(length: tabs.length, vsync: this);
    _tabController.addListener(() {
      debugPrint("tab tapped at ${_tabController.index}");
    });
    EasyLoading.show();
    Future.delayed(const Duration(milliseconds: 2000)).then((value) {
      EasyLoading.dismiss();
    });

    logoutlistener = NetworkUtil.registerLogoutListener(() { 
      doLogout();
    });

    super.initState();
  }

  @override
  void dispose() {
    //release resource here
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return NotificationListener<LogoutActionNotification>(
      child: buildNormalWidget(context),
      onNotification: (notification) {
        Navigator.pop(context);
        AlertHelper.showAlert(
          context: context,
          message: "Are you sure you want to log out?",
          onPressed: () {
            doLogout();
          },
        );
        return true;
      },
    );
  }

  void doLogout(){
    AppHelper.shared.logout(() {
          Navigator.of(context).push(RawDialogRoute(pageBuilder: (context, animation, secondaryAnimation) {
            return FutureBuilder(future: login_page.loadLibrary(),builder:((context, snapshot) => login_page.LoginPage(afterLogin: ((p0) {
            Navigator.pop(context);
            LoginActionNotification("logged in").dispatch(context);
        }))));
      },));
  });
}

  PreferredSizeWidget _buildAppBarAtIndex(int index) {
    return [
      AppBar(
        // title: Text(AppLocalizations.of(context)!.homePage),
        elevation: 0,
        title: TabBar(
          isScrollable: true,
          controller: _tabController,
          labelStyle:
              const TextStyle(decorationStyle: TextDecorationStyle.solid),
          tabs: tabs
              .map((e) => Container(
                    constraints: const BoxConstraints(
                      minWidth: 50,
                    ),
                    child: Tab(
                      text: e,
                    ),
                  ))
              .toList(),
        ),
      ),
      AppBar(
        title: const Text("Page Business"),
      ),
      AppBar(
        title: const Text("Notifications"),
      )
    ][index];
  }

  Widget _buildBodyAtIndex(int index) {
    return [
      TabBarView(
        controller: _tabController,
        children: [
          const HomeContent1(),
          FutureBuilder(future:home_content2.loadLibrary(),builder: ((context, snapshot) => home_content2.HomeContent2())),
          FutureBuilder(future:home_content3.loadLibrary(),builder: ((context, snapshot) => home_content3.HomeContent3())),
          // HomeContent4(),
          // HomeContent5(),
          FutureBuilder(future:home_content_last.loadLibrary(),builder: ((context, snapshot) => home_content_last.HomeContentLast())),
        ],
      ),
      const Center(
        child: Text("Business detail"),
      ),
      const Center(
        child: Text("Notices"),
      ),
    ][index];
  }

  Widget buildNormalWidget(BuildContext context) {
    var mainView = Scaffold(
      appBar: _buildAppBarAtIndex(_currentIndex),
      drawer: const MySideMenu(),
      // endDrawer: MySideMenu(),
      body: _buildBodyAtIndex(_currentIndex),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _currentIndex,
        items: <BottomNavigationBarItem>[
          BottomNavigationBarItem(
              icon: const Icon(Icons.production_quantity_limits_rounded),
              label: Intl.message("Products", locale: "zh-cn")),
          const BottomNavigationBarItem(
              icon: Icon(Icons.business_outlined), label: "Business"),
          BottomNavigationBarItem(
              icon: Stack(
                children: [
                  const Icon(Icons.miscellaneous_services_rounded),
                  Positioned(
                    right: 0,
                    child: Container(
                        alignment: Alignment.center,
                        width: 15,
                        height: 15,
                        decoration: const BoxDecoration(
                            shape: BoxShape.circle, color: Colors.red),
                        child: const Text(
                          "1",
                          style: TextStyle(color: Colors.white),
                        )),
                  )
                ],
              ),
              label: "Notifications"),
        ],
        selectedItemColor: Colors.amber[800],
        onTap: (value) {
          setState(() {
            _currentIndex = value;
          });
        },
      ),

      floatingActionButton: Badge(
        borderRadius: const BorderRadius.all(Radius.circular(10)),
        position: const BadgePosition(top: -5, end: -5),
        badgeColor: Colors.blue,
        showBadge: true,
        badgeContent: const Text(
          "3",
          style: TextStyle(color: Colors.white),
        ),
        child: FloatingActionButton(
          onPressed: () {
            Navigator.of(context).pushNamed("/chat");
          },
          tooltip: 'ChatEntry',
          child: const Icon(Icons.chat),
        ),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
    return mainView;

    /// wrap the mainview with notificationlistener.
    // return DefaultTabController(initialIndex: 0, length: 3, child: mainView);
  }
}
